package com.lanou3g.hw0419.question3;

import java.io.*;

/**
 * Created by dllo on 18/4/20.
 */
public class Main {
    public static void main(String[] args) {
        String rootPath = "/Users/dllo/Desktop/19号作业/Q2";
        String targetPath = "/Users/dllo/Desktop/19号作业/Q3";
        File file = new File(rootPath);
        for (File file1 : file.listFiles()) {
            if (file1.isFile() && file1.length() >= 1024 * 1024 * 1024) {
                spilt(file1, targetPath);
            }
        }
    }


    //file 要拆的文件
    //targetPath 拆完放哪--Q3文件夹
    public static void spilt(File file, String targetPath) {
        File targetDir = new File(targetPath, file.getName());
        //创建文件夹
        targetDir.mkdirs();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        int index = 0;//第几个文件
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int pos = 0;
            byte[] buf = new byte[1024];
            File desFile = new File(targetDir, file.getName() + index);
            bos = new BufferedOutputStream(new FileOutputStream(desFile));
            long size = 0;

            while ((pos = bis.read(buf)) != -1) {
                //写流
                bos.write(buf, 0, pos);
                //每写400M bos就指向新的文件
                size += pos;
                if (size >= 400 * 1024 * 1024) {
                    bos.close();//把原来的流关了
                    index++;//下一个文件
                    size = 0;//大小重新统计
                    //bos 指向新的文件
                    bos = new BufferedOutputStream(new
                            FileOutputStream(new File(targetDir, file.getName())));
                }
            }
            //while 循环外面,别写错大括号位置了
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
